package com.dingreading.cloud.admin.config;

import com.mybatisflex.core.datasource.FlexDataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Component
public class DataSourceChecker implements CommandLineRunner {

    @Autowired
    private DataSource dataSource; // 这里注入的是 FlexDataSource

    @Override
    public void run(String... args) throws Exception {
        System.out.println("注入的数据源类型: " + dataSource.getClass().getName());

        if (dataSource instanceof FlexDataSource) {
            FlexDataSource flexDataSource = (FlexDataSource) dataSource;
            // 获取默认数据源（或者你知道的某个特定数据源的 key）
            DataSource defaultTargetDataSource = flexDataSource.getDefaultDataSource();
            // 或者遍历所有数据源
            // Map<String, DataSource> allDataSources = flexDataSource.getAllDataSources();

            System.out.println("默认目标数据源类型: " + defaultTargetDataSource.getClass().getName());

            // 检查这个目标数据源是否是 HikariCP
            if (defaultTargetDataSource instanceof HikariDataSource) {
                HikariDataSource hikariDataSource = (HikariDataSource) defaultTargetDataSource;
                System.out.println("✅ HikariCP 作为底层连接池已生效！");
                System.out.println("JDBC Url: " + hikariDataSource.getJdbcUrl());
                System.out.println("最大连接池大小: " + hikariDataSource.getMaximumPoolSize());
                System.out.println("Pool Name: " + hikariDataSource.getPoolName());
                System.out.println("Connection Timeout: " + hikariDataSource.getConnectionTimeout() + "ms");
                System.out.println("Idle Timeout: " + hikariDataSource.getIdleTimeout() + "ms");
                System.out.println("Max Lifetime: " + hikariDataSource.getMaxLifetime() + "ms");
                System.out.println("Minimum Idle: " + hikariDataSource.getMinimumIdle());
                System.out.println("Keep aliveTime: " + hikariDataSource.getKeepaliveTime());

                // 可以打印更多 HikariCP 的配置信息
            } else {
                System.out.println("❌ 默认目标数据源不是 HikariCP，而是: " + defaultTargetDataSource.getClass().getName());
            }
        }
    }
}
